package com.tang.portal.facade.admin.sys;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tang.framework.core.domain.HttpResult;
import com.tang.framework.core.model.LoginUser;
import com.tang.common.model.req.ReqId;
import com.tang.common.constant.Constant;
import com.tang.common.model.req.ReqIds;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.tang.service.admin.domain.SysRoleMenu;
import com.tang.service.admin.model.req.ReqSysRoleMenu;
import com.tang.service.admin.model.req.ReqSysRoleMenuAdd;
import com.tang.service.admin.model.res.ResSysRoleMenuTableItem;
import com.tang.service.admin.model.res.ResSysRoleMenuDetail;
import com.tang.service.admin.service.ISysRoleMenuService;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.BeanUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static com.tang.common.utils.excel.ExcelUtils.getStyleStrategy;
/**
 * @author tang jun liang
 * @Date ${gen.dateTime}
 */
@Service
public class SysRoleMenuFacade {

    @Resource
    private ISysRoleMenuService sysRoleMenuService;



    /**
     * 角色菜单删除
     * @param ids
     * @param currLoginUser
     * @return
     */
    public HttpResult<String> remove(ReqIds ids, LoginUser currLoginUser) {
        sysRoleMenuService.removeBatchByIds(ids.getIds());
        return HttpResult.ok();
    }

    /**
     * 角色菜单详情
     * @param id
     * @param currLoginUser
     * @return
     */
    public HttpResult<ResSysRoleMenuDetail> detail(ReqId id, LoginUser currLoginUser) {
        SysRoleMenu sysRoleMenu = sysRoleMenuService.getById(id.getId());
        ResSysRoleMenuDetail resSysRoleMenuDetail = new ResSysRoleMenuDetail();
        BeanUtils.copyProperties(sysRoleMenu, resSysRoleMenuDetail);
        return HttpResult.ok(resSysRoleMenuDetail);
    }

    /**
     * 角色菜单列表
     * @param reqSysRoleMenu
     * @param currLoginUser
     * @return
     */
    public HttpResult<IPage<ResSysRoleMenuTableItem>> list(ReqSysRoleMenu reqSysRoleMenu, LoginUser currLoginUser) {
        IPage<ResSysRoleMenuTableItem> page = sysRoleMenuService.selectJoinListPage(
                new Page<>(reqSysRoleMenu.getPageNum(), reqSysRoleMenu.getPageSize()),
                ResSysRoleMenuTableItem.class,
                new MPJLambdaWrapper<SysRoleMenu>()
                        .selectAll(SysRoleMenu.class)
        );
        return HttpResult.ok(page);
    }

    /**
     * 新增角色菜单
     * @param sysRoleMenuAdd
     * @return
     */
    public HttpResult<String> add(ReqSysRoleMenuAdd sysRoleMenuAdd) {
        SysRoleMenu sysRoleMenu = new SysRoleMenu();
        BeanUtils.copyProperties(sysRoleMenuAdd, sysRoleMenu);
        sysRoleMenuService.saveOrUpdate(sysRoleMenu);
        return HttpResult.ok();
    }

    /**
     * 更新角色菜单
     * @param sysRoleMenuAdd
     * @return
     */
    public HttpResult<String> update(ReqSysRoleMenuAdd sysRoleMenuAdd) {
        return add(sysRoleMenuAdd);
    }



    /**
     * 导出角色菜单表
     *
     * @param ids
     * @param httpServletResponse
     */
    @SneakyThrows
    public void export(ReqIds ids, HttpServletResponse httpServletResponse) {
        String fileName = URLEncoder.encode("角色菜单.xlsx", StandardCharsets.UTF_8);
        // 设置响应体
        httpServletResponse.setContentType("application/vnd.ms-excel");
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setHeader("Content-disposition", "attachment;filename=" + fileName);
        List<SysRoleMenu> sysRoleMenuList = sysRoleMenuService
                .lambdaQuery()
                .in(!ids.getIds().isEmpty(), SysRoleMenu::getId, ids.getIds())
                .list();
        EasyExcel.write(httpServletResponse.getOutputStream(),SysRoleMenu.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .registerWriteHandler(getStyleStrategy())
                .sheet("角色菜单").doWrite(sysRoleMenuList);
    }


    /**
     * 导入excel
     *
     * @param file
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public HttpResult<String> importExcel(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        EasyExcel.read(inputStream, ReqSysRoleMenuAdd.class, new AnalysisEventListener<ReqSysRoleMenuAdd>() {
            final List<SysRoleMenu> sysRoleMenuList = new ArrayList<>();
            @Override
            public void invoke(ReqSysRoleMenuAdd sysRoleMenuAdd, AnalysisContext analysisContext) {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                BeanUtils.copyProperties(sysRoleMenuAdd, sysRoleMenu);
                sysRoleMenuList.add(sysRoleMenu);
                if (sysRoleMenuList.size() == Constant.MAX_BATCH){
                    sysRoleMenuService.saveBatch(sysRoleMenuList);
                    sysRoleMenuList.clear();
                }
            }
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                sysRoleMenuService.saveBatch(sysRoleMenuList);
            }
        });
        return HttpResult.ok();
    }

    /**
     * 导出模版
     * @param httpServletResponse
     */
    @SneakyThrows
    public void exportTemplate(HttpServletResponse httpServletResponse) {
        String fileName = URLEncoder.encode("角色菜单导入模版.xlsx", StandardCharsets.UTF_8);
        // 设置响应体
        httpServletResponse.setContentType("application/vnd.ms-excel");
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setHeader("Content-disposition", "attachment;filename=" + fileName);
        EasyExcel.write(httpServletResponse.getOutputStream(), SysRoleMenu.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .registerWriteHandler(getStyleStrategy())
                .sheet("角色菜单").doWrite(List.of());
    }

}
